<title>消息列表</title>

<div class="layui-fluid">
  <div class="layui-card">
    <form class="layui-form layui-card-header layuiadmin-card-header-auto" lay-filter="LAY_message_list_form">
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">消息标题</label>
          <div class="layui-input-block">
            <input type="text" name="title" placeholder="请输入" autocomplete="off" class="layui-input">
          </div>
        </div>

        <div class="layui-inline">
          <button class="layui-btn layuiadmin-btn-useradmin" lay-submit lay-filter="LAY_message_list_search">
            <i class="layui-icon layui-icon-search layuiadmin-button-btn"></i> 查询
          </button>
          <button type="reset" class="layui-btn layuiadmin-btn-useradmin">
            <i class="layui-icon layui-icon-refresh layuiadmin-button-btn"></i> 重置
          </button>
          <button type="button" class="layui-btn layuiadmin-btn-useradmin LAY_message_list_add">
            <i class="layui-icon layui-icon-addition layuiadmin-button-btn"></i> 新增推送
          </button>
        </div>
      </div>
    </form>

    <div class="layui-card-body">
      <table id="LAY_message_list" lay-filter="LAY_message_list"></table>

      <script type="text/html" id="LAY_message_list_toolbar" lay-filter="LAY_message_list_toolbar">
        {{# if (d.status == 'EDITING') { }}
        <a class="layui-btn layui-btn-xs LAY_btn_list_edit" lay-event="edit">继续编辑</a>
        {{# } }}
        {{# if (d.status == 'READY') { }}
        <a class="layui-btn layui-btn-xs LAY_btn_list_revoke" lay-event="revoke">撤销推送</a>
        <a class="layui-btn layui-btn-xs LAY_btn_list_modify" lay-event="modify">修改</a>
        {{# } }}
      </script>
    </div>

  </div>
</div>

<script>
  layui.use(['admin', 'form', 'element', 'laypage', 'laytpl', 'table', 'getmenus'], function () {
    var $ = layui.$,
            admin = layui.admin,
            setter = layui.setter,
            view = layui.view,
            table = layui.table,
            laytpl = layui.laytpl,
            laypage = layui.laypage,
            element = layui.element,
            form = layui.form,
            getmenus = layui.getmenus,
            params = {};

    // 初始化表单
    form.render(null, 'LAY_message_list_form');
    initPermission();

    // 表单提交
    form.on('submit(LAY_message_list_search)', function (data) {
      var field = data.field;
      params = $.extend(true, params, field);

      reloadMessageList(params, 1);
      return false;
    });

    initMessageList();
    initEvents();

    // 初始化table
    function initMessageList() {
      var field = form.val('LAY_revenue_detail_form');
      params = $.extend(true, params, field);

      table.render({
        elem: '#LAY_message_list'
        ,where: $.extend(true, {}, params)
        ,page: true
        ,url: setter.url + '/message/list' //模拟接口
        ,data: []
        ,cols: [[
          { field: 'messageId', align: 'center', title: '消息ID', templet: function (d) {
              return '<a class="LAY_url_a" lay-href="/message/detail/messageId=' + d.messageId + '">'+ d.messageId +'</a>'
            }}
          ,{ field: 'createdTime', align: 'center', title: '创建时间' }
          ,{ field: 'title', align: 'center', title: '消息主题' }
          ,{ field: 'sentTime', align: 'center', title: '推送时间' }
          ,{ field: 'effectTime', align: 'center', title: '生效时间' }
          ,{ field: 'statusDesc', align: 'center', title: '推送状态', templet: function (d) {
              var color = '#e17575';

              switch (d.status) {
                case 'READY':
                  color = '#d3b556';
                  break;
                case 'EDITING':
                  color = '#40b1a6';
                  break;
                case 'SENT':
                  color = '#c3c3c3';
                  break;
                default:
              }

              return d.status ? '<span style="color: ' + color + '">' + d.statusDesc + '</span>' : '';
            }}
          ,{ title: '操作', width: 300, align: 'center', fixed: 'right',  toolbar: '#LAY_message_list_toolbar' }
        ]]
        ,parseData: function(res){
          return {
            "code": res.code,
            "msg": res.msg,
            "data": res.data.list,
            "count": res.data.pageInfo.count
          };
        }
        ,response: {
          statusCode: 200 //规定成功的状态码，默认：0
        }
        ,request: {
          limitName: 'pageSize'
        }
        ,done: function () {
          initTablePermission();
        }
      });

      table.on('tool(LAY_message_list)', function(obj){
        var data = obj.data;

        switch (obj.event) {
          case 'edit':
            layerShow('edit', data.messageId, data.status);
            break;
          case 'revoke':
            cancelMessage(data.messageId, function () {
              reloadMessageList(params);
              layer.msg('操作成功', {
                icon: 1,
                time: 1500,
                shade: [0.3, '#393D49']
              });
            });
            break;
          case 'modify':
            layerShow('modify', data.messageId, data.status);
            break;

          default:
            break;
        }
      });
    }

    // reload table
    function reloadMessageList(params, curr, callback) {
      table.reload('LAY_message_list', {
        where: params,
        page: { curr: curr }
        ,done: function (res) {
          initTablePermission();
          if (typeof(callback) == 'function') {
            callback(res);
          }
        }
      })
    }

    function initEvents() {
      $('.LAY_message_list_add').off('click').on('click', function () {
        layerShow();
      });
    }

    // 显示编辑页
    function layerShow(optType, messageId, status) {
      var btn = ['提交', '暂存', '取消'];

      if (status == 'READY') {
        btn = ['提交', '取消'];
      }

      var settings = {
        type: 2
        ,title: messageId ? (optType == 'modify' ? '修改消息推送' : '继续编辑推送消息') : '新增消息推送'
        ,area: ['80%', '680px']
        ,content: '#/message/form/messageId=' + messageId
        ,btn: btn //只是为了演示
        ,yes: function(index, layero){
          var iframe = getIframeWindow(layero);
          var data = iframe.getData();
          var optCode = 1;

          if (optType == 'modify') {
            optCode = 2
          }

          data = $.extend(true, {}, data, {
            optCode: optCode,
            messageId: messageId
          });

          layer.getChildFrame('body', index).find('#LAY_message_form_submit').click();

          if (!verify(data)) {
            return false;
          }

          updataMessage(data, function () {
            layer.msg('操作成功', {
              icon: 1,
              time: 1500,
              shade: [0.3, '#393D49']
            });

            reloadMessageList(params);
            layer.close(index);
          });

          return false;
        }
      }

      if (status == 'READY') {
        settings.btn2 && delete settings.btn2;
      } else {
        settings.btn2 = function(index, layero){
          var iframe = getIframeWindow(layero);
          var data = iframe.getData();

          data = $.extend(true, {}, data, {
            optCode: 0,
            messageId: messageId
          });

          layer.getChildFrame('body', index).find('#LAY_message_form_submit').click();

          if (!verify(data)) {
            return false;
          }

          updataMessage(data, function () {
            layer.msg('操作成功', {
              icon: 1,
              time: 1500,
              shade: [0.3, '#393D49']
            });

            reloadMessageList(params);
            layer.close(index);
          });

          return false;
        }
      }

      var index = layer.open(settings);
    }

    // 获取iframe
    function getIframeWindow(layero) {
      var win = window[layero.find('iframe')[0]['name']];
      return win;
    }

    // 变更消息
    function updataMessage(params, callback) {
      var url = '/message/create';

      if (params.messageId) {
        url = '/message/update'
      }

      admin.req({
        url: setter.url + url,
        type: 'POST',
        data: params,
        done: function () {
          if (typeof(callback) == 'function') {
            callback();
          }
        }
      });
    }

    // 撤销消息
    function cancelMessage(messageId, callback) {
      layer.confirm('你确定要撤销推送吗？', function(index, layero){
        layer.msg('正在撤销', {
          icon: 16,
          time: 1500,
          shade: [0.3, '#393D49']
        }, function(){
          admin.req({
            url: setter.url + '/message/cancel',
            type: 'POST',
            data: { messageId: messageId },
            done: function () {
              if (typeof(callback) == 'function') {
                callback();
              }
            }
          })
        });
      });
    }

    function verify(field) {
      if (!field.title) {
        return false;
      }

      if (!field.effectTime) {
        return false;
      }

      var targetTime = new Date(field.effectTime).getTime();
      var currentTime = new Date().getTime();
      if (targetTime < currentTime) {
        return false;
      }

      if (!field.content) {
        layer.msg('消息内容不能为空', {
          icon: 2,
          anim: 6
        });
        return false;
      }

      if (!field.deliveryTargets.length) {
        layer.msg('目标机构不能为空', {
          icon: 2,
          anim: 6
        });
        return false;
      }

      return true;
    }

    function initPermission() {
      // 消息管理-新增
      var addBtn = $('.LAY_message_list_add');

      if (!getmenus.messageAdd) {
        addBtn.remove();
      }
    }

    function initTablePermission() {
      // 消息管理-编辑
      var editBtn = $('.LAY_btn_list_edit');

      if (!getmenus.messageEdit) {
        editBtn.remove();
      }

      // 消息管理-撤销
      var revokeBtn = $('.LAY_btn_list_revoke');

      if (!getmenus.messageDel) {
        revokeBtn.remove();
      }

      // 消息管理-修改
      var modifyBtn = $('.LAY_btn_list_modify');

      if (!getmenus.messageUpdate) {
        modifyBtn.remove();
      }
    }

  });
</script>